#!/bin/bash


echo -e "\033[4mTrafficPanel installation script.\033[0m\n"

if [ `whoami` != "root" ]; then
    echo -e '\E[31m'"\033[1mError: \033[0m Configuration script requires \033[1mroot\033[0m privileges.\n"
    exit
fi

if [ -e '/selinux/enforce' ]; then
    if [ `sestatus | grep "SELinux status" | gawk '{print $3}'` = 'enabled' ] || [ "`cat /selinux/enforce`" = "1" ]; then
if [ `cat /selinux/enforce` = '1' ]; then
       echo "TrafficPanel can not work with enabled SELinux"
   exit
fi
    fi
fi

res=''
function getItem()
{
    res=''
    for item in $( echo $1 ); do
       if [ -e "$item" ]; then
           res=$item
           break
       fi
    done
}
function readConf() {
       echo "Please enter location for $1:"
       read CONF
       if [ ! "$CONF" ] || [ ! -e "$CONF" ]; then
               echo "$CONF file has not been found."
               readConf $1
       fi
}

function get_tool()
{
    res=''
    util=$1
       for item in `$whereis -b $1`; do
               if [ `echo "$item" | $grep -Ec ".+/$1$"` == "1" ]; then
			if [ ! -d $item ] && [ -x $item ]; then
	                       res=$item
        	               break
			fi
               fi
       done;
       if [ ! -n "$res" ]; then
               writeErrorMessage $util, $util;
       elif [ -n "$res" ] && [ ! -x "$res" ]; then
               writeErrorMessage $util, $util;
       fi
}

function getBin()
{
    res=''
    bin=`$whereis $1|$gawk {'print $2'}`
    if [ `echo "$bin"|$grep -Ec ".+/$1$"` != '1' ]; then
       writeErrorMessage $1, $2
    else
       res=$bin
    fi
}

function checkConf()
{
    if [ "$1" != '' ] && [ -e "$1" ]; then
       echo -e "[\E[32mok\033[0m]"
    else
       echo -e '\n\E[31m'"\033[1merror:\033[0m $1 ['$2'] has not been found.\n"
              readConf $1 $2
    fi
}

function CHECK_PERL_MODULES() {

   RES=`perldoc -rlm $1|$wc -l`
   echo $RES
}

function writeErrorMessage()
{
       echo ""
       echo -e '\E[31m'"\033[1mError: \033[0m \033[1m$1\033[0m has not been found.";
       echo "Installation aborted."
       echo -e "Please install \033[1m$2\033[0m and run TrafficPanel installation again."
    exit
}


############################################################
# BEGIN SECTION
SQUIDGUARD_CONFS='/etc/squidguard.conf /etc/squid/squidGuard.conf /etc/squid/squidGuard.conf.rpmnew'
SARG_CONFS='/etc/sarg.conf /etc/sarg/sarg.conf /etc/squid/sarg.conf'
NAMED_CONFS='/etc/named.conf /etc/bind/named.conf'
PERL_MODULES=('CGI Carp::Clan XML::Simple Date::Calc Storable IPC::ShareLite XML::SAX') #Net::SMTP::TLS

SQUID_CONF='/etc/squid/squid.conf'
getItem "$NAMED_CONFS"; NAMED_CONF=$res
getItem "$SARG_CONFS"; SARG_CONF=$res
getItem "$SQUIDGUARD_CONFS"; SQUIDGUARD_CONF=$res
SQUIDGUARD_DBHOME='/var/lib/squidGuard/db'
SQUIDGUARD_LOGDIR='/var/log/squidGuard'
#SQUIDGUARD_BASES_URL='http://squidguard.mesd.k12.or.us/blacklists.tgz'

apache_user='apachetwm'
apache_group='apachetwm'

set_permissions="1"

# END SECTION
############################################################
#    Unix system utils.

whereis='whereis'
gawk=`which 'gawk' 2>/dev/null`
if [ ! -n "$gawk" ]; then
    echo "Installation require gawk util. Please install gawk and run configure script again."
    exit 1;
fi
grep=`$whereis 'grep'|$gawk '{print $2}'`

echo -n -e "Looking for required unix utils  .......... "
#    Tools used by installation script and different TrafficPanel scripts.
get_tool 'sed'; sed=$res
get_tool 'make'; make=$res
get_tool 'chown'; chown=$res
get_tool 'chgrp'; chgrp=$res
get_tool 'chmod'; chmod=$res
get_tool 'useradd'; useradd=$res
get_tool 'groupadd'; groupadd=$res
get_tool 'tar'; tar=$res
get_tool 'ifconfig'; ifconfig=$res
get_tool 'netstat'; netstat=$res
get_tool 'hostname'; hostname=$res
get_tool 'ls'; ls=$res
get_tool 'ln'; ln=$res
get_tool 'head'; head=$res
get_tool 'cat'; cat=$res
get_tool 'seq'; seq=$res
get_tool 'wc'; wc=$res
get_tool 'rm'; rm=$res
get_tool 'cp'; cp=$res
get_tool 'mkdir'; mkdir=$res
get_tool 'touch'; touch=$res
get_tool 'mv'; mv=$res
get_tool 'pwd'; pwd=$res
get_tool 'find'; find=$res
get_tool 'ps'; ps=$res
get_tool 'cut'; cut=$res
#get_tool 'wget'; wget=$res
get_tool 'sha1sum'; sha1sum=$res
get_tool 'date'; date=$res
get_tool 'gzip'; gzip=$res
get_tool 'kill'; kill=$res
get_tool 'route'; route=$res
get_tool 'pppd'; pppd=$res
get_tool 'ethtool'; ethtool=$res
get_tool 'iptables'; iptables=$res
get_tool 'du'; du=$res
get_tool 'tail'; tail=$res
get_tool 'ip'; ip=$res
get_tool 'gcc'; gcc=$res
get_tool 'perldoc'; perldoc=$res
if [ `$perldoc -V | $grep -c "Perldoc v"` == 0 ]; then
	writeErrorMessage 'perldoc', 'perldoc';
fi

IS_UBUNTU=`uname -a | $grep -c Ubuntu`
IS_DEBIAN=`uname -a | $grep -c debian`

if [ "$IS_UBUNTU" == "1" ] || [ "$IS_DEBIAN" == "1" ]; then
	get_tool 'update-rc.d'; updatercd=$res
else
	get_tool 'chkconfig'; chkconfig=$res
fi

echo -e "[\E[32mok\033[0m]"


inst_folder=`$pwd`

#    Check is /etc/profile exists.
echo -n "Looking for '/etc/profile'   .......... "
profile_file='/etc/profile'
if [ ! -e "$profile_file" ]; then
       echo "Can not find $profile_file."
       echo "Installation aborted."
       exit 1
fi
echo -e "[\E[32mok\033[0m]"
echo -n "Looking for '/etc/environment'   .......... "
environment_file=''
if [ ! -e "/etc/environment" ]; then
	environment_file="/etc/environment"
fi
echo -e "[\E[32mok\033[0m]"


echo -e "\nLooking for installed packages"
echo -n "Looking for bind   .......... ";getBin 'named' 'bind'; named_bin=$res;echo -e "[\E[32mok\033[0m]"
echo -n "Looking for squid   .......... ";getBin 'squid' 'squid'; squid_bin=$res;echo -e "[\E[32mok\033[0m]"
echo -n "Looking for sarg   .......... ";getBin 'sarg' 'sarg'; sarg_bin=$res;echo -e "[\E[32mok\033[0m]"
echo -n "Looking for squidGuard   .......... ";getBin 'squidGuard' 'squidGuard'; squidGuard_bin=$res;echo -e "[\E[32mok\033[0m]"
echo -n "Looking for named config file    .......... ";checkConf "$NAMED_CONF" 'named.conf'
echo -n "Looking for squid config file    .......... ";checkConf "$SQUID_CONF" 'squid.conf'
echo -n "Looking for sarg config file    .......... ";checkConf "$SARG_CONF" 'sarg.conf'
echo -n "Looking for squidGuard config file    .......... ";checkConf "$SQUIDGUARD_CONF" 'squidGuard.conf'

#    Installing required perl modules.
echo "Looking for perl modules"
echo $PERL_MODULES | sed "s/ / , /g"
PERL_MM_USE_DEFAULT=1
if [ `CHECK_PERL_MODULES 'CPAN'` != 1 ]; then
    writeErrorMessage 'CPAN', 'CPAN'
fi


for item in $( echo $PERL_MODULES ); do
    if [ `CHECK_PERL_MODULES "$item"` != 1 ]; then
           echo -e "\n$item required perl module is not installed."
           echo "Do you want install it manually from distributive package (recomended) [y/n] ?"
       while true
       do
           read ans
           case $ans in
           y|Y)
		echo "Please install $item perl module and run configure script again."
		echo "FYI: ./perl_modules.sh downloads and installs latest modules version from CPAN."
		exit 1
		break;;
           n|N)
		perl -MCPAN -e 'install $item';
		break;;
           *)
               echo -e "Please enter [y/n]";;
           esac
       done
    fi
    if [ `CHECK_PERL_MODULES "$item"` != 1 ]; then
       echo -e "\nPlease install '$item' and run $0 again."
	echo "You can run ./perl_modules.sh to download and install modules from CPAN"
       exit 1
    fi
done
if [ ! -e "`perldoc -rlm XML::SAX | sed -e 's/.pm//'`/ParserDetails.ini" ]; then
    perl -MXML::SAX -e "XML::SAX->add_parser(q(XML::SAX::PurePerl))->save_parsers()"
fi
# echo -e "[\E[32mok\033[0m]"

#    Define installation folder.
TWM_INSTALLATION_DIR='/usr/local/twm'
echo -n -e "\nTrafficPanel folder [$TWM_INSTALLATION_DIR] : "
read ans
if [ $ans ]; then
       TWM_INSTALLATION_DIR=$ans
fi

if [ `$cat $profile_file | $grep -c "export TWMFOLDER"` == '0' ]; then
	echo "TWMFOLDER=$TWM_INSTALLATION_DIR" >> $profile_file
	echo "export TWMFOLDER" >> $profile_file
	if [ -n "$environment_file" ] && [ `$cat $environment_file | $grep -c "export TWMFOLDER"` == "0" ]; then
		echo "TWMFOLDER=$TWM_INSTALLATION_DIR" >> $environment_file
		echo "export TWMFOLDER" >> $environment_file
	fi
fi

source '/etc/profile'
export TWMFOLDER=$TWM_INSTALLATION_DIR

if [ ! -d "$TWMFOLDER" ]; then
       $mkdir -p $TWMFOLDER
else
       echo -e "\033[1m$TWMFOLDER\033[0m already exists.\n"
fi

#    Define domain name.
hname=`$hostname`
echo -n "Server name [$hname] : "
read ans
if [ $ans ]; then
       hname=$ans
fi
dname='local'
echo -n "Domain name [$dname] : "
read ans
if [ $ans ] ; then
       dname=$ans
fi
echo ""

#    Apache installation/configuration.
	echo -n "Looking for installed apache   .......... "
	apache_bin=`whereis -b httpd | sed 's/ /\n/g' | while read item ; do if [ -f $item ] && [ \`echo "$item"|grep -c \/httpd$\` == '1' ]; then echo $item; fi done;`
	is_apache='1'
	if [ -z "$apache_bin" ] || [ ! -e $apache_bin ]; then
		apache_bin=`whereis -b httpd2 | sed 's/ /\n/g' | while read item ; do if [ -f $item ] && [ \`echo "$item"|grep -c \/httpd2$\` == '1' ]; then echo $item; fi done;`
		is_apache='2'
	fi
	if [ -z "$apache_bin" ] || [ ! -e $apache_bin ]; then
		apache_bin=`whereis -b apache2 | sed 's/ /\n/g' | while read item ; do if [ -f $item ] && [ \`echo "$item"|grep -c \/apache2$\` == '1' ]; then echo $item; fi done;`
	fi

	if [ -z "$apache_bin" ] || [ ! -e $apache_bin ]; then
		echo ""
		echo -e '\E[31m'"\033[1mError:\033[0m apache binary has not been found. Please install apache package manually."
		exit 1
	fi
	echo -e "[\E[32mok\033[0m]"

	echo "Configuring virtual host for installed apache"

	apache_user=`$cat /etc/passwd|$grep -E "www|apache"|$gawk -F: '{print $1}'`
	if [ ! $apache_user ]; then
		echo  "Can not find apache user, please enter apache user name:"
		read apache_user
	fi
	apache_group=`$cat /etc/group|$grep -E "www|apache"|$gawk -F: '{print $1}'`
	if [ ! $apache_group ]; then
		echo "Can not find apache group, please enter apache group name:"
		read apache_group
	fi
	./apacheVH_setup.sh "$hname.$dname" "$is_apache"

TWMlink=`$grep 'link:' /tmp/twm.installation|$gawk -F: '{print $2":"$3":"$4}'`
IP=`$grep 'ip:' /tmp/twm.installation|$gawk -F: '{print $2}'`
PORT=`$grep 'port:' /tmp/twm.installation|$gawk -F: '{print $2}'`
if [ $PORT = '80' ]; then
    TWMlink2="http://$IP/"
else
    TWMlink2="http://$IP:$PORT/"
fi
TWM_APACHE=`$grep 'twm_apache:' /tmp/twm.installation|$gawk -F: '{print $2}'`

$rm -Rf /tmp/twm.installation


#    Creation templates with direct/reverse zones for named.
echo -n "DNS modification                 .......... "
function createZoneFiles()
{
       declare -a contents

       num=`$cat ./domain_templates/$1|$wc -l`
       for ((i=1; i<=$num; i++));
       do
           contents[$i-1]=`$sed -n "${i}p; ${i}q" ./domain_templates/$1`
       done

       if [ -e "./domain_templates/$4" ];then
               $rm "./domain_templates/$4"
       fi

       for element in $($seq 0 $((${#contents[@]} - 1)))
       do
           echo "${contents[$element]}"|$gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "./domain_templates/$4"
       done
}
createZoneFiles 'TEMPLATE.ca' 'DOMAIN_NAME' "$dname" "$dname.ca"
createZoneFiles "$dname.ca" 'HOST_NAME' "$hname" "$dname.ca"
createZoneFiles "$dname.ca" 'HOST_IP' "$IP" "$dname.ca"
createZoneFiles 'TEMPLATE.lan' 'DOMAIN_NAME' "$dname" "$dname.lan"

$cp "./domain_templates/$dname.ca" ../template/kernel/
$cp "./domain_templates/$dname.lan" ../template/kernel/
echo -e "[\E[32mok\033[0m]"

NETWORKADDR="192.168.1.0/24"
NETWORKADDR_DATA=(192 168 1 0 24)
BIT_MASK=(31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 8)

readNetworkIP () {
	IS_NETWORKADDR=0
        echo -n "Please enter network address [$NETWORKADDR]: "
        read ans
        if [ "$ans" ]; then
		data=(`echo $ans | $gawk -F. '{print $1" "$2" "$3" "$4}' | $gawk -F/ '{print $1" "$2}'`)
		if [ ${data[0]} -gt 0 ] && [ ${data[0]} -lt 256 ] && [ ${data[1]} -ge 0 ] && [ ${data[1]} -lt 256 ] && [ ${data[2]} -ge 0 ] && [ ${data[2]} -lt 256 ] && [ ${data[3]} -ge 0 ] && [ ${data[3]} -lt 256 ] ; then
			for item in ${BIT_MASK[*]}
			do
				if [ $item = ${data[4]} ]; then
					IS_NETWORKADDR=1
					break
				fi
			done
		fi
		if [ $IS_NETWORKADDR = 1 ]; then
			NETWORKADDR=$ans
			for ((i=0; i<=${#NETWORKADDR_DATA}; i++)); do
				NETWORKADDR_DATA[$i]=${data[$i]}
			done
		else
			echo "You set wrong network address."
			readNetworkIP
		fi
        fi
}

readNetworkIP


echo ""
echo -n "Looking for BIND working directory    .......... "
if [ -e "$NAMED_CONF.local" ]; then
	NAMED_CONF="$NAMED_CONF.local"
	BIND_WORKING_DIR="/etc/bind/zones"
	if [ ! -e $BIND_WORKING_DIR ]; then
		mkdir $BIND_WORKING_DIR
	fi
else
	BIND_WORKING_DIR=`$grep -v '#' $NAMED_CONF|$grep -E "directory \".+\""|$gawk -F'"' '{print $2}'`
fi

readBinddir () {
	echo "Please enter BIND working directory :"
	read BIND_WORKING_DIR
	if [ ! "$BIND_WORKING_DIR" ] || [ ! -d "$BIND_WORKING_DIR" ]; then
               echo "$BIND_WORKING_DIR directory has not been found."
               readBinddir
       fi
}
if [ ! -n "$BIND_WORKING_DIR" ]; then
	echo ""
	echo -e '\E[31m'"\033[1merror:\033[0m BIND working directory has not been found."
	readBinddir
else
	echo -e "[\E[32mok\033[0m]"
fi

if [ `$grep -c "zone \"$dname\"" $NAMED_CONF` = "0" ]; then
		echo -e "\nzone \"$dname\" {
               type master;
           notify no;
               file \"$BIND_WORKING_DIR/$dname.ca\";
};

zone \"${NETWORKADDR_DATA[2]}.${NETWORKADDR_DATA[1]}.${NETWORKADDR_DATA[0]}.in-addr.arpa\" {
               type master;
           notify no;
               file \"$BIND_WORKING_DIR/$dname.lan\";
};" >> $NAMED_CONF
fi

$grep -v '\[direct_zone_ip_list\]' "./domain_templates/$dname.ca" > "$BIND_WORKING_DIR/$dname.ca"
$grep -v '\[reverse_zone_ip_list\]' "./domain_templates/$dname.lan" > "$BIND_WORKING_DIR/$dname.lan"



#    Modification squid.conf.
if [ `$grep -Ec "^visible_hostname" $SQUID_CONF` = "0" ]; then
    echo -n "Modification SQUID config file                .......... "
    echo -e "visible_hostname $hname" >> $SQUID_CONF
    SQUID_VERSION=`$squid_bin -v|$grep 'Version'|$gawk '{print $4}'|$cut -d. -f1,2`
    IS_SQUID_OLD=`gawk -v OLD_SQUID_VER="2.5" -v CUR_SQUID_VER="$SQUID_VERSION" 'BEGIN { if (CUR_SQUID_VER<=OLD_SQUID_VER) {print "1"} else {print "0"} }'`

    if [ $IS_SQUID_OLD = "1" ]; then
       echo "redirect_program $squidGuard_bin -c $SQUIDGUARD_CONF" >> $SQUID_CONF
    else
       echo "url_rewrite_program $squidGuard_bin -c $SQUIDGUARD_CONF" >> $SQUID_CONF
    fi
    echo -e "[\E[32mok\033[0m]"
fi

#    Modification sarg.conf.
if [ `$grep -c "# TrafficPanel custom settings" $SARG_CONF` = "0" ]; then
    if [ ! -e "$SARG_CONF.bak" ]; then
       mv $SARG_CONF "${SARG_CONF}.bak"
    fi
    echo -n "Modification SARG config file                .......... "
    $cat $SARG_CONF | $sed -e "s/^resolve_ip.*//g" -e "s/^user_ip.*//g" -e "s/^topuser_sort_field.*//g" -e "s/^user_sort_field.*//g" -e "s/^lastlog.*//g" -e "s/^index.*//g" -e "s/^topsites_sort_order.*//g" -e "s/^replace_index.*//g" > $SARG_CONF
    echo -e "\n
# TrafficPanel custom settings
resolve_ip yes
user_ip yes
topuser_sort_field BYTES reverse
user_sort_field BYTES reverse
lastlog 150
index yes
topsites_sort_order BYTES D
replace_index <?php echo str_replace(".", "_", $REMOTE_ADDR); echo ".html"; ?>
" >> $SARG_CONF
    echo -e "[\E[32mok\033[0m]"
fi

#    Modification squidGuard.conf.
if [ ! -e "$SQUIDGUARD_CONF.bak" ]; then
    mv $SQUIDGUARD_CONF "${SQUIDGUARD_CONF}.bak"
fi

#echo -n "squidGuard databases folder [$SQUIDGUARD_DBHOME] : "
#read ans
#if [ "$ans" ]; then
#       squidGuarddbhome=$ans
#fi
if [ ! -d "$SQUIDGUARD_DBHOME" ]; then
       $mkdir -p $SQUIDGUARD_DBHOME
fi

#echo -n "squidGuard log folder [$SQUIDGUARD_LOGDIR] : "
#read ans
#if [ "$ans" ]; then
#       squidGuardlogdir=$ans
#fi
if [ ! -d "$SQUIDGUARD_LOGDIR" ]; then
       $mkdir -p $SQUIDGUARD_LOGDIR
fi

echo ""

echo "
dbhome $SQUIDGUARD_DBHOME
logdir $SQUIDGUARD_LOGDIR
" > $SQUIDGUARD_CONF

declare -a dblist
dblist=( $(dir "$SQUIDGUARD_DBHOME") )
for element in $($seq 0 $((${#dblist[@]} - 1)))
do
   if [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/domains" ] && [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/urls" ]; then
echo "dest ${dblist[$element]} {
   domainlist ${dblist[$element]}/domains
   urllist ${dblist[$element]}/expressions
   }" >> $SQUIDGUARD_CONF
   elif [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/domains" ]; then
echo "dest ${dblist[$element]} {
   domainlist ${dblist[$element]}/domains
}" >> $SQUIDGUARD_CONF
   elif [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/urls" ]; then
echo "dest ${dblist[$element]} {
   urllist ${dblist[$element]}/urls
}" >> $SQUIDGUARD_CONF
   fi
done

echo "
acl {
     default {
     }
}
" >> $SQUIDGUARD_CONF


#    Compiling squidGuard bases.
echo "Compiling SquidGuard bases."
$squidGuard_bin -c $SQUIDGUARD_CONF -C all
echo -e "SquidGuard bases compiled                  .......... [\E[32mok\033[0m]\n"
echo ""

if [ ! -e "/etc/squid/squidguard.conf" ]; then
    $ln -s $SQUIDGUARD_CONF "/etc/squid/squidguard.conf"
fi
#    setting appropriate permissions to squidGuard databases folder.
$chmod -R 775 $SQUIDGUARD_DBHOME
$chown -R root:$apache_group $SQUIDGUARD_DBHOME


############################################################
#    Edit and compile sources.
############################################################
echo -n "Compiling sources                  .......... "
function editCsources ()
{
       declare -a content
       num=`$cat ./src/$1/${1}.c | $wc -l`
       for ((i=1; i<=$num; i++));
       do
               content[$i-1]=`$sed -n "${i}p; ${i}q" ./src/$1/${1}.c`
       done
       if [ -e "./src/$1/${1}.c" ]; then
               $rm "./src/$1/${1}.c"
       fi
       for element in $(seq 0 $((${#content[@]} - 1)))
       do
               echo "${content[$element]}"| $gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "./src/$1/${1}.c"
       done
}

editCsources 'forker' '*twmfolder = argv\\[1\\];' "*twmfolder = \"$TWMFOLDER\";"
editCsources 'runner' '*twmfolder = "\\[TWMFOLDER\\]";' "*twmfolder = \"$TWMFOLDER\";"

cd ./src/forker/
./compile.sh $apache_group
cd ../../
cd ./src/runner/
./compile.sh $apache_group
cd ../../
echo -e "[\E[32mok\033[0m]"

#    Copy TrafficPanel sources.
echo -n "Copying TrafficPanel files                .......... "
$cp -R ../* $TWMFOLDER
echo -e "[\E[32mok\033[0m]"

#    Modification startup scripts.
echo -n "Modification startup scripts                .......... "
TWMFOLDER_SKIPPED=`echo $TWMFOLDER | sed -e 's|/|\\\/|g'`
$cat ../bin/twm.sh | $sed -e "s/^TWMFOLDER=TWMFOLDER/TWMFOLDER=$TWMFOLDER_SKIPPED/g" > $TWMFOLDER/bin/twm.sh
$cat ../bin/init.sh | $sed -e "s/^export TWMFOLDER=TWMFOLDER/export TWMFOLDER=$TWMFOLDER_SKIPPED/g" > $TWMFOLDER/bin/init.sh
$cat ../bin/set_logs_permission.sh | $sed -e "s/^\tchown APACHE_USER:APACHE_GROUP/\tchown $apache_user:$apache_group/g" > $TWMFOLDER/bin/set_logs_permission.sh
echo -e "[\E[32mok\033[0m]"

echo -n "Setting appropriate file permissions                .......... "
if [ $set_permissions ]; then
    cd $TWMFOLDER
    $chown -R root:$apache_group ./
    $chmod 640 `$find . -type f|$grep -v 'apache/bin'`
    $chmod 750 `$find . -type d`
    $chmod 750 `$find . -name \*.sh`
    $chmod 750 `$find . -name \*.pl`
    $chmod 660 `$find . -name \*.xml`
    $chmod 660 `$find . -name \*.conf`
    $chmod 640 `$find . -name \*.pm`
    $chmod 770 $TWMFOLDER/backup
    $chmod -R g+w $TWMFOLDER/logs
    $chmod -R g+w $TWMFOLDER/etc/passwd
    $chmod 4750 ./bin/runner
    $chmod 4750 ./bin/forker
    $chown root:$apache_group "$BIND_WORKING_DIR/$dname.ca"
    $chown root:$apache_group "$BIND_WORKING_DIR/$dname.lan"
    $chmod 664 "$BIND_WORKING_DIR/$dname.ca"
    $chmod 664 "$BIND_WORKING_DIR/$dname.lan"
    $chmod 770 ./modules/shaping_cbq/cbq

# modules customization.
    $chmod 750 "$TWMFOLDER/modules/http_ip_limit/httpr_sl"
    $chmod 750 "$TWMFOLDER/modules/shaping_cbq/cbq.init"
    $chmod 750 "$TWMFOLDER/modules/if_meter/traff_meter"
    $chmod 664 $SQUID_CONF
    $chown root:$apache_group $SQUID_CONF
    $chmod 664 $SQUIDGUARD_CONF
    $chown root:$apache_group $SQUIDGUARD_CONF

    if [ ! -d '/etc/squid/delay' ]; then
       mkdir '/etc/squid/delay'
    fi

    if [ -d '/etc/squid/delay' ]; then
       $chmod 770 '/etc/squid/delay'
       $chown root:$apache_group '/etc/squid/delay'
    fi

    if [ ! -e "/sbin/tc" ]; then
       $ln -s /usr/sbin/tc /sbin/tc
    fi

fi
echo -e "[\E[32mok\033[0m]"
echo ""

# for future using
#if [ -e '/selinux' ]; then
#    if [ `sestatus | grep "SELinux status" | gawk '{print $3}'` = 'enabled' ] || [ `cat /selinux/enforce` == '1' ]; then
#        chcon -R -t httpd_sys_script_exec_t $TWMFOLDER
#        chcon -R -t httpd_sys_rw_content_t $TWMFOLDER/logs/
#        chcon -R -t bin_t $TWMFOLDER/bin/runner
#        chcon -R -t bin_t $TWMFOLDER/bin/forker
#    fi
#fi

#    Modification TrafficPanel config.
cd "$TWMFOLDER/install"
perl ./manage_config.pl dns _domain_name="$dname" _named_direct_zone="$dname.ca" _named_reverse_zone="$dname.lan" _named_zone_dir="$BIND_WORKING_DIR" subnetwork="$NETWORKADDR"
# setting correct path for each unix tool used by TrafficPanel exclude 'whereis' and 'gawk' utils.
perl ./manage_config.pl system_scripts grep="$grep" sed="$sed" ls="$ls" sha1sum="$sha1sum" date="$date" gzip="$gzip" tar="$tar" cat="$cat" seq="$seq" route="$route" ps="$ps" wc="$wc" pppd="$pppd" ethtool="$ethtool" ifconfig="$ifconfig" hostname="$hostname" iptables="$iptables" named="$TWMFOLDER/bin/named.sh" du="$du" tail="$tail" touch="$touch" ip="$ip" mv="$mv" find="$find" netstat="$netstat" rm="$rm" cp="$cp" mkdir="$mkdir" kill="$kill" gawk="$gawk"
# setting variables containing $TWMFOLDER.
perl ./manage_config.pl common_twm _kernel_template="$TWMFOLDER/template/kernel" cgfolder="$TWMFOLDER/www/cgi-bin/" conf_backup_folder="$TWMFOLDER/backup/" scfolder="$TWMFOLDER/bin/" twmfolder="$TWMFOLDER/"


#    Set default admin login and password.
set_auth () {
       login='admin'
       echo -n "Please enter TrafficPanel administrator login name [$login] : "
       read ans
       if [ $ans ]; then
               login=$ans
       fi
       set_passwd () {
               echo -n -e "\033[1mPlease enter password : \033[0m" #\030
               read passwd
               if [ $passwd ]; then
                       echo -n -e "\033[1mConfirm password :  \033[0m"
                       read passwd2
                       if [ $passwd2 ]; then
                               if [ $passwd = $passwd2 ]; then
                                       perl ./addLogin.pl $login $passwd
                               else
                                       echo "Passwords do not match."
                                       set_passwd
                               fi
                       else
                               echo "Password can not be empty. Please try again."
                               set_passwd
                       fi
               else
                       echo "Password can not be empty. Please try again."
                       set_passwd
               fi
       }
       set_passwd
}
set_auth
echo ""

cd $inst_folder
$rm -fR "$TWMFOLDER/install"

if [ ! -e '/etc/init.d/twm.sh' ]; then
    $ln -s "$TWMFOLDER/bin/twm.sh" '/etc/init.d/twm.sh'
fi

if [ $TWM_APACHE = "1" ]; then
    echo -e "\nStarting TrafficPanel apache."
    $TWMFOLDER/apache/bin/apachectl start
elif [ -e '/etc/init.d/httpd' ]; then
    /etc/init.d/httpd restart
else
    service apache2 restart
fi


$TWMFOLDER/bin/named.sh restart
if [ "$IS_UBUNTU" == "1" ] || [ "$IS_DEBIAN" == "1" ]; then
	$updatercd twm.sh defaults
else
	$chkconfig --add twm.sh
	$chkconfig --level 345 named on
	if [ `$chkconfig --list | $grep -c httpd` == 1 ]; then
		$chkconfig --level 345 httpd on
	elif [ `$chkconfig --list | $grep -c apache2` == 1 ]; then
		$chkconfig --level 345 apache2 on
	else
		echo -e "\033[1mCan not enable apache service \033[0m"
	fi

fi

/etc/init.d/twm.sh restart

###########################################################################
# DONE
###########################################################################


echo -e "\nTrafficPanel files has been installed in \033[1m$TWMFOLDER.\033[0m"
echo -e "\nIf you installed from \033[1mX\033[0m gui please restart it before use TrafficPanel there."
echo -e "Use \033[4m$TWMlink\033[0m or \033[4m$TWMlink2\033[0m to get web access with your favorite browser."
echo -e "Define local network hosts IP in the 'TrafficPanel'->'Setup'->'Local network hosts'."


exit 0